class SendMailAction < WorkflowAction
  validates_presence_of :recipients
  
  def valid_input_classes
    [String]
  end
  
  def output_class
    TMail::Mail
  end
  
  def mailer
    options[:mailer].nil? ? WorkflowMailer : options[:mailer].constantize
  end
  
  def mailer=(mailer_class)
    if (mailer_class.class != Class or ! mailer_class.respond_to?(:deliver))
       raise "#{mailer_class.to_s} does not respond to #deliver"
    end
    options[:mailer] = mailer_class.to_s
  end
  
  def deliver_method
    options[:deliver_method] || :deliver_workflow
  end
  
  def from
    options[:from] || default_from
  end
  
  # This is here so that the validation picks it up
  # There's probably a better way to do it
  def recipients
    options[:recipients]
  end

  def input_mime_type
    if higher_item.respond_to?(:mime_type)
      higher_item.mime_type
    else
      "text/plain"
    end
  end
  
  def input_filename
    return nil unless higher_item.respond_to?(:filename)
    higher_item.filename   
  end
  
  def execute
    mailer.send(deliver_method, 
                workflow, 
                recipients, 
                from, 
                { :content   => input,
                  :filename  => input_filename,
                  :mime_type => input_mime_type 
                })
  end
  
  protected
  
  def default_from
    begin
      WORKFLOW_MAIL_FROM
    rescue
      "root@yourhost.com"
    end
  end
end